package com.atnjupt.threadlocal;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;

/**
 * @author Wizarder
 * @create 2021-06-15 17:48
 */
public class ThreadLocalTest {
    public static Map<String,Object> data = new Hashtable<>();
    public static  ThreadLocal<Object> threadLocal = new ThreadLocal<>();
    public static  ThreadLocal<Object> threadLocal1 = new ThreadLocal<>();
    private static Random random = new Random();

    public static  class  Task implements Runnable{
        @Override
        public void run() {
            threadLocal.set("aa");
            threadLocal1.set("bb");
            Object o = threadLocal.get();
            Object o2 = threadLocal1.get();
            System.out.println(o);
            System.out.println(o2);
        }


       /* @Override
        public void run() {
            // 在Run方法中，随机生成一个变量（线程要关联的数据），然后以当前线程名为key保存到map中
            int i = random.nextInt(1000);//0-999的三位随机数
            //获取当前线程名
            String name = Thread.currentThread().getName();
            threadLocal.set(i);
//            data.put(name,i);
            System.out.println("线程[" + name + "]放入数据：" + i);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //从data中取出来
//            Object o = data.get(name);
//            new OrderService().createOrder();
            Object o = threadLocal.get();
            System.out.println("从线程[" + name + "]中取出来的数据为：" + o);


        }*/
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(new Task()).start();
        }
    }
}

